import React, { DragEvent } from 'react';
import { Sortable } from './sortable';
import { closest } from '../utils';


export default function Row ({ children, className, index }: any) {
  const __onDrop = (event: DragEvent <HTMLElement>) => {
    event.preventDefault();
    event.stopPropagation();
    const node = closest(event.nativeEvent.target as HTMLElement, 'droppable');
    const transfer = event.dataTransfer.getData('drag:data');

    console.log('__onDrop', event)
    if (!transfer) return

    try {
      const dataTransfer: { index: string, data: any } = JSON.parse(transfer);
      // 提交数据
      const data = {
        // 目标位置
        nextIndex: node?.dataset.index,
        // 来源位置
        prevIndex: dataTransfer.index,
        data: dataTransfer.data 
      }
      if (typeof data.nextIndex !== 'undefined') {
        data.nextIndex = `${data.nextIndex}-${index > 0 ? index : 0}`
      } else {
        data.nextIndex = `${index > 0 ? index : 0}`
      }
    } catch (error) {
      return console.log(error)
    } finally {
      // 清空拖拽的数据
      event.dataTransfer.clearData();
    }
  }
  
  return (
    <Sortable
      className={`row ${className}`}
    >
      { children }
    </Sortable>
  )
}

